package com.hzhr.iot.comm.controller;


import com.hzhr.iot.comm.Global;
import com.hzhr.iot.comm.model.CommandResponseModel;
import com.hzhr.iot.comm.model.CommonResponseModel;
import com.hzhr.iot.comm.model.HttpResult;
import com.hzhr.iot.comm.model.ReceiveCommandModel;
import com.hzhr.iot.comm.service.HttpAPIService;
import com.hzhr.iot.comm.util.RedisUtil;
import com.hzhr.iot.core.util.HzhrJsonUtil;
import com.hzhr.iot.huaweiiot.sdk.model.command.postCommand.PostCommandModel;
import com.hzhr.iot.huaweiiot.sdk.service.Huaweiiot_CommandService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "command-receiver", description = "命令接收器")
@RestController
public class CommandReceiver {
    @Autowired
    HttpAPIService httpAPIService;
    @Value("${uri}")
    String uri;
    @Autowired
    Huaweiiot_CommandService huaweiiot_commandService;
    @Autowired
    Global global;
    @Autowired
    RedisUtil redisUtil;

    private static Logger logger = LoggerFactory.getLogger(CommandReceiver.class);

    @RequestMapping(value = "/commands/receive", method = RequestMethod.POST)
    public CommonResponseModel receiveCommand(
            @RequestBody @ApiParam(name="receiveCommandDto(发送命令请求对象)", required=true) ReceiveCommandModel requestBody)
            throws Exception {
        logger.info("/commands/receive   body:" + HzhrJsonUtil.object2json(requestBody));

        Date receiveTime = new Date();//服务器接收时间

        String message = null;

        HttpResult result = httpAPIService.doPostByBody(uri, HzhrJsonUtil.object2json(requestBody));

        if (result != null) {
            String body = result.getBody();
            if (!StringUtils.isEmpty(body)) {
                try {
                    CommandResponseModel commandResponseModel = HzhrJsonUtil.json2object(body, CommandResponseModel.class);
                    if (commandResponseModel != null) {
                        Integer senderId = commandResponseModel.getSenderId();
                        String deviceId = commandResponseModel.getDeviceId();
                        Integer expireTime = commandResponseModel.getExpireTime();
                        List<String> respMsgList = commandResponseModel.getRespMsgList();
                        if (respMsgList != null && respMsgList.size() > 0) {
                            if (senderId != null) {
                                if (senderId == 1) {
                                    int expire = 0;
                                    for (String respMsg:
                                            respMsgList) {
                                        Map<String, String> header = new HashMap<>();
                                        header.put("token", global.getFirstToken());
                                        Map<String, Object> query = new HashMap<>();
                                        PostCommandModel postCommandModel = new PostCommandModel();
                                        postCommandModel.setCommand(respMsg);
                                        postCommandModel.setDeviceId(deviceId);
                                        postCommandModel.setExpireTime(0);
                                        Thread.sleep(expireTime * 1000);
                                        try {
                                            huaweiiot_commandService.postCommand(header, query, postCommandModel);
                                        } catch (Throwable e) {

                                        }

                                        expire += expireTime;
                                    }
                                }

                                if (senderId == 2) {
                                    int expire = 0;
                                    for (String respMsg:
                                            respMsgList) {
                                        String key = "socket_service:resp_command" + deviceId + ":";
                                        redisUtil.lPush(key, respMsg);

                                        expire += expireTime;
                                    }
                                }
                            }
                        }
                    }
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
        }

        return new CommonResponseModel();
    }
}



